<template>
  <Layout>
    <Form ref="form1" :model="form1" :label-width="120">
      <Row v-show="switchFlag" class="query-form" style="padding-top: 15px">
        <Col span="8">
          <FormItem label="审计计划：">
            <Select v-model="form1.planId" style="width: 100%">
              <Option v-for="plan in planList" :key="plan.auditPlanId" :value="plan.auditPlanId">
                {{ plan.auditPlanName }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="排序规则：">
            <Select v-model="form1.order" style="width: 100%">
              <Option value="1">总分</Option>
              <Option value="2">基础分数</Option>
              <Option value="3">现场分数</Option>
              <Option value="4">班组分数</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="审计类型：">
            <Select v-model="form1.auditType" style="width: 100%">
              <Option value="1">专项检查</Option>
              <Option value="2">安全审计</Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form" style="padding-top: 15px">
        <Col span="8">
          <FormItem label="二级集团：">
            <two-level-org class="query-form-el" v-model="form1.twoOrgId"></two-level-org>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="被审计单位：">
            <company-select root v-model="form1.orgName" class="w"></company-select>
          </FormItem>
        </Col>
        <Col span="8">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>

        </Col>
      </Row>
      <Row v-show="!switchFlag" class="query-form" style="padding-top: 15px">
        <Col span="8">
          <FormItem label="审计计划：">
            <Select v-model="form1.planId" style="width: 100%">
              <Option v-for="plan in planList" :key="plan.auditPlanId" :value="plan.auditPlanId">
                {{ plan.auditPlanName }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="排序规则：">
            <Select v-model="form1.order" style="width: 100%">
              <Option value="1">总分</Option>
              <Option value="2">基础分数</Option>
              <Option value="3">现场分数</Option>
              <Option value="4">班组分数</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-cloud-download" :loading="buttonLoading"  @click="download">审计排行导出</Button>
        </Col>
      </Row>
    </Form>

    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据！" @on-selection-change="reportSelect"
           :loading="buttonLoading" size="small" border :columns="columns1" :data="dataTable"  >
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              style="float: right" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
              show-total show-sizer show-elevator/>
      </Col>
    </Row>

    <Modal title="分数修正" :transfer=false v-model="model2" :width=400>
      <Form ref="modelAndView" :model="modelAndView" :rules="ruleCustom" label-position="top">
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="分数调整：" >
              <InputNumber style="width: 100%;"  v-model="modelAndView.score"></InputNumber>
            </FormItem>
          </Col>
          <Col span="23">
            <FormItem label="调整分数说明：" >
              <Input v-model="modelAndView.scoreDesc" type="textarea" :rows="3"/>
            </FormItem>
          </Col>
        </Row>

      </Form>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="submit('modelAndView')" :loading="submitLoading">确定</Button>
        <Button class='ivu-btn-cancel' @click="handleCancel">取消</Button>
      </div>
    </Modal>
  </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import {sessionStorage} from '@/common/cacheUtils.js';
import {formatDate} from "@/tools";

var cascaderDom = () => import('@/components/cascader-dom.vue');

export default {
  components: {
    cascaderDom
  },
  data() {
    return {
      jinyu:[],
      planList:[],
      submitLoading:false,
      modelAndView:{},
      addLoading:false,
      crrentUser: sessionStorage('userId').getObject('userId'),
      expertSelectModal: false,
      currentUser: JSON.parse(sessionStorage('userId').get('userId')),
      locationList: [],
      stdRankList: [],
      supervisors: [],
      downloadUrl: Api.downloadMongoFile,
      upUrl: Api.uploadMongoFile,
      switchFlag: false,
      form1: {},
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      dataTable: [],
      columns1: [

        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          title: '二级集团',
          minWidth: 280,
          align: 'center',
          fixed: 'left',
          key: 'twoOrgName',
        },
        {
          title: '审计单位',
          minWidth: 280,
          align: 'center',
          fixed: 'left',
          key: 'orgName',
        },
        {
          title: '审计计划',
          minWidth: 150,
          align: 'center',
          key: 'auditPlanName',
        },
        {
          title: '审计任务',
          minWidth: 150,
          align: 'center',
          key: 'missionName',
        },
        {
          title: '带队',
          minWidth: 80,
          align: 'center',
          key: 'supervisor',
        },
        {
          title: '组长',
          minWidth: 80,
          align: 'center',
          key: 'groupLeaderName',
        },

        {
          title: '成员',
          minWidth: 300,
          align: 'center',
          key: 'membersName',
        },
        {
          title: '基础标准得分',
          minWidth: 150,
          align: 'center',
          key: 'calculationBasicsScore',
          render: (h, params) => {
            return h('span', params.row.calculationBasicsScore ||'--');
          }
        },
        {
          title: '现场标准得分',
          minWidth: 150,
          align: 'center',
          key: 'calculationSceneScore',
          render: (h, params) => {
            return h('span', params.row.calculationSceneScore ||'--');
          }
        },
        {
          title: '班组标准得分',
          minWidth: 150,
          align: 'center',
          key: 'calculationTeamScore',
          render: (h, params) => {
            return h('span', params.row.calculationTeamScore ||'--');
          }
        },
        {
          title: '总分',
          minWidth: 150,
          align: 'center',
          key: 'totalScore',
        },
        {
          title: '得分率',
          minWidth: 150,
          align: 'center',
          key: 'scoreRate',

        },
        {
          title: '调整分数说明',
          minWidth: 200,
          align: 'center',
          key: 'scoreDesc',

        },
        {
          title: '集团综合增减',
          minWidth: 150,
          align: 'center',
          key: 'finalScore',
          render: (h, params) => {
            return h('div', [
              h('span', Math.floor((params.row.finalScore - params.row.totalScore) * 100) / 100  )
            ]);
          }

        },
        {
          title: '最终得分',
          minWidth: 150,
          align: 'center',
          key: 'finalScore',

        },
        {
          title: '评级',
          minWidth: 150,
          align: 'center',
          key: 'level',

        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          minWidth: 120,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                },
                on: {
                  click: () => {
                    this.showData(params);
                  }
                }
              }, '修改'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    style: {
                      fontSize: '14px'
                    },
                    on: {
                      click: () => {
                        this.downloadFile(params.row);
                      }
                    }
                  }, '导出'),
                ]);

          }
        },

      ],
      ruleCustom: {
      },
      auditedOrgName: '',
      auditedOrgId: '',
      basics: [],
      basicsMap: {},
      reportSelectAll:[],
      scene: [],
      sceneMap: {},
      add: false,
      model1: false,
      model2: false,
      showdata: {},
      location: null,
      form1datacopy: {},
      files: [],
      buttonLoading: false, tableHeight: 10,
    }
  },
  mounted() {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    //this.selectCodingSort();
    this.getPlanAll();
    this.query();
  },
  methods: {
    getPlanAll(){
      let _this = this;
      this.$http.get(Api.getPlanTwoAll).then((res) => {

        _this.planList = res.data.data.list
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    rectLeaderChange(appStatus) {
      if (appStatus) {
        this.form1datacopy.supervisorId = appStatus.value;
        this.form1datacopy.supervisor = appStatus.label;
      }
    },
    auditTypesChange(stdRank) {
      if (stdRank) {
        this.form1datacopy.auditTypeId = stdRank.value;
        this.form1datacopy.auditTypeName = stdRank.label;
      }
    },
    downloadFile(data) {
      this.$http.get(Api.downLoadAuditTwoMission+data.missionId, {
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = data.orgName+"_"+"审计分值分布(" + formatDate(new Date(), "yyyy-MM-dd") + ").xlsx" //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    selectPlan(value, selectedData){
      if (value.length != 0){
        if (value[0]){
          this.form1.planId = value[0];
        }
        if (value[1]){
          this.form1.year = value[1];
        }else{
          delete this.form1.year;
        }
      }else{
        delete this.form1.planId;
        delete this.form1.year;
      }

    },
    download() {
      let data = Object.assign(JSON.parse(JSON.stringify(this.form1)));
      this.$http.get(Api.downLoadAuditTwoMissionRank, {
        params: data,
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = "审计排行(" + formatDate(new Date(), "yyyy-MM-dd") + ").xlsx" //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    openExpertSelector(isLeader) {
      this.$refs.selExpert.isLeader = isLeader
      this.$refs.selExpert.form2 = {
        members: this.form1datacopy.membersName ? this.form1datacopy.membersName : '',
        membersId: '',
        membersUserId: ''
      },

          //console.log('1111',this.form1datacopy)
          this.selectUsers = []
      let hasVal = this.form1datacopy.membersId && this.form1datacopy.membersId.length > 1
      let mId = hasVal ? this.form1datacopy.membersId.split(',') : []
      let mName = hasVal ? this.form1datacopy.membersName.split(',') : []
      let mUId = hasVal ? this.form1datacopy.membersUserId.split(',') : []
      let i = 0
      mId.forEach(v => {
        let userInfo = {name: mName[i], expertId: v, userId: mUId[i]}
        i++
        this.selectUsers.push(userInfo)
      })

      this.expertSelectModal = true;
    },
    onCancel() {
      this.model2 = false
    },
    closeModal1() {
      this.expertSelectModal = false;
      this.selectUsers = []
    },
    getActivityData(row) {
      console.log('getActivityData(row)', row)
      if (this.$refs.selExpert.isLeader == 1) {
        this.form1datacopy.groupLeaderId = row.expertId;
        this.form1datacopy.groupLeaderName = row.userName;
        this.form1datacopy.groupLeaderUserId = row.userId;
        this.expertSelectModal = false;
      } else {
        this.form1datacopy.membersId = row.membersId.join(',')
        this.form1datacopy.membersName = row.members.join(',')
        this.form1datacopy.membersUserId = row.membersUserId.join(',')
      }
    },

    selectLocation(location) {
      this.form1datacopy.locationId = location.value;
      this.form1datacopy.location = location.label;
    },
    selectstdRank(stdRank) {
      this.form1datacopy.stdRankId = stdRank.value;
      this.form1datacopy.stdRank = stdRank.label;
    },
    selectAppStatus(appStatus) {
      this.form1datacopy.appStatusId = appStatus.value;
      this.form1datacopy.appStatus = appStatus.label;
    },
    reportSelect(select) {
      this.reportSelectAll = [];
      select.forEach(item => {
        this.reportSelectAll.push(item.missionId)
      });
      console.log(this.reportSelectAll)
    },
    beforeUploadOther(file) {
      this.files.push(file);

      return false;
    },
    submitReportSelect(){
      let _this = this;
      let config = {
        title: '系统提示',
        content: '确认完成审计?',
        okText: '确定',
        cancelText: '取消',
        onOk: function () {
          this.$http.post(Api.submitSelectAuditTwoMission, _this.reportSelectAll).then((res) => {
            if (res.data.status == '200') {
              _this.$Message.success("确认成功");
              _this.query();
            } else {
              _this.$Message.success(res.data.msg);
              _this.query();
            }

          }).catch(e => {
            this.query();
            this.$Message.error("失败")
          })

        }

      }


      this.$Modal.confirm(config);
    },
    deleteFile(index) {
      this.files.splice(index, 1);
    },
    setOrgId(data) {
      this.form1datacopy.auditedOrgId = data[data.length - 1];
    },
    setOrgName(data) {
      this.form1datacopy.auditedOrgName = data;
    },
    deleteData(params) {
      this.$Modal.confirm({
        title: '数据删除',
        content: '<p>确定删除该条信息</p>',
        okText: '确认',
        onOk: () => {
          let url = Api.deleteAuditTwoMission;
          this.$http.get(url, {params: {id: params.row.missionId}}).then((res) => {
            if (res.status === 200) {
              this.$Message.success('成功');
              this.query()
            } else if (res.data.status === 201) {
              this.$Message.error(res.data.msg);

            }
          }).catch(e => {
            this.$Message.error('请求失败' + e);
          })
        },
        cancelText: '取消'
      });
    },


    getSelectRows(rows) {
      this.deleteRows = rows;
    },
    batDelete() {

    },
    addInfo() {
      let userName = JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createUserName"]
      this.form1datacopy = {
        createDate: this.formatDate(new Date(), 'yyyy-MM-dd'),
        createUserName: userName,
        auditPlanName: this.curPlan.auditPlanName,
        auditPlanId: this.curPlan.auditPlanId,
        planStartTime: this.curPlan.planStartTime,
        planEndTime: this.curPlan.planEndTime
      };
      this.auditedOrgName = '';
      this.auditedOrgId = '';
      this.model1 = true;
      this.add = true;
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    handleCancel() {
      this.modelAndView = {};
      this.model2 = false;
    },
    forMap(arr) {
      let map = {};
      arr.forEach(item => {
        map[item["id"]] = item["standardsName"]
      })
      return map;
    },
    selectCodingSort() {
      this.$http.get(Api.queryTwoJinyu).then((res) => {
        this.jinyu = res.data.data;


      });

    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (!this.switchFlag) {
        this.tableHeight = window.innerHeight - 220;
      } else {
        this.tableHeight = window.innerHeight - 315;
      }
    },
    reset() {
      this.form1 = {};
      // this.$refs.queryOrg.resetCurrentOrg();
      this.query();


    },
    query() {
      this.buttonLoading = true;
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
      };
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      let url = Api.queryAuditTwoRank;
      this.$http.get(url, {params: data}).then((res) => {
        this.dataTable = res.data.data.data;
        this.pagedata.total = res.data.data.totalSize;
        this.buttonLoading = false;
      }).catch(e => {
        this.$Message.error("数据获取失败")
        this.buttonLoading = false;
      })
    },
    showData(data) {
     //分数model
      this.modelAndView = JSON.parse(JSON.stringify(data.row));
      this.modelAndView.renduScore = this.modelAndView.finalScore - (this.modelAndView.finalScore * 2);
      this.modelAndView.score = 0;
      this.model2 = true;
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },

    submit(name) {
      let _this = this;
      this.$refs[name].validate((valid) => {
        if (valid) {
          _this.submitLoading = true;
          this.$http.post(Api.updateAuditTwoRank, this.modelAndView).then((res) => {
            if (res.data.status == '200') {
              this.$Message.success('成功');
              this.model2 = false;
              this.query()

            } else if (res.data.status == '201') {
              this.$Message.error(res.data.data);
              this.model2 = false;
            }
            _this.submitLoading = false;

          }).catch(e => {
            _this.submitLoading = false;
            this.model2 = false;
            this.query();
            this.$Message.error("数据获取失败")
          })
        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },

  },
  watch: {
    "model1": function (qw, er) {
      if (qw && this.model1) {
        setTimeout(() => {
          this.$refs.trainOrg.setCurrentOrg();

        }, 100)
      } else {
        this.$refs.trainOrg.setCurrentOrg();

      }
    },

    "expertSelectModal": function (qw, er) {
      if (qw && this.model1) {
        setTimeout(() => {
          //this.$refs.trainOrg.setCurrentOrg();

        }, 100)
      } else {
        this.$refs.selExpert.reset();

      }
    },

  },


}
</script>

<style lang='css' scoped>
@import '../../../index.css';
</style>
